package pro.softzhang.algo.lc2300;

import pro.softzhang.algo.flag.x.XOptimal;

/**
 * https://leetcode.cn/problems/removing-stars-from-a-string/solution/zhan-de-jing-dian-ying-yong-by-endlessch-ljym/
 */
public class LC2390_RemovingStarsFromAString {
    public static void main(String[] args) {
        String s = "leet**cod*e";
        System.out.println(new Solution1().removeStars(s));
    }

    /**
     * StringBuilder
     */
    static
    class Solution {
        public String removeStars(String s) {
            // 字符串
            StringBuilder sb = new StringBuilder(s.length());
            for(int i = 0; i < s.length(); i++) {
                char ch = s.charAt(i);
                if(ch == '*') {
                    sb.deleteCharAt(sb.length() - 1);
                } else {
                    sb.append(ch);
                }
            }
            return sb.toString();
        }
    }

    /**
     * Array模拟栈
     */
    @XOptimal
    static
    class Solution1 {
        public String removeStars(String s) {
            char[] chArr = new char[s.length()];
            int j = 0;
            for(int i = 0; i < s.length(); i++) {
                char ch = s.charAt(i);
                if(ch != '*') {
                    chArr[j++] = ch;
                } else {
                    j--;
                }
            }
            return new String(chArr, 0, j);
        }
    }
}
